from config.MyEnv import MyEnv
from config.db import MySQLClient
import json
from flask import jsonify
from config.db_config import db_config, tenant_db_config, refact_db_config
from service.common_service import get_request_body
import uuid

db_client = MySQLClient(db_config)
tenant_db_client = MySQLClient(tenant_db_config)
refact_db_client = MySQLClient(refact_db_config)


def long_to_guid(long_id):
    """
    将雪花算法生成的Long类型ID转换为GUID/UUID格式

    参数:
        long_id: 雪花算法生成的Long类型ID

    返回:
        标准GUID/UUID字符串
    """
    # 将Long类型转换为16字节的字节串
    bytes_val = long_id.to_bytes(16, byteorder='big', signed=False)

    # 从字节串创建UUID对象
    guid = uuid.UUID(bytes=bytes_val)

    return str(guid)

def sql_value(v):
    if v is None:
        return 'NULL'
    if isinstance(v, bool):
        return '1' if v else '0'
    if isinstance(v, (int, float)):
        return str(v)
    if isinstance(v, str):
        return "'" + v.replace("'", "''") + "'"
    return "'" + str(v).replace("'", "''") + "'"

def upgrade_accessor():
    sql = 'select id,tenant_code,code,action,name,type,parent_id,description,extra from mum_accessor'
    records = db_client.query(sql)
    insert_sqls = []
    columns = ['accessorguid', 'tenantcode', 'code', 'action', 'name', 'type', 'parentid', 'description', 'extra']

    for record in records:
        record = list(record)
        if record[0]:
            record[0] = long_to_guid(record[0])
        if record[6]:
            record[6] = long_to_guid(record[6])
        values = [sql_value(v) for v in record]
        insert_sql = f"INSERT INTO ggfw_mum_accessor ({', '.join(columns)}) VALUES ({', '.join(values)});"
        insert_sqls.append(insert_sql)

    show_sql = ('<br>'.join(insert_sqls) + '<br>') if insert_sqls else ''
    return show_sql

# python
def upgrade_strategy():
    sql = 'select id,code,name,type,description,channel_type,scene_code,version from mum_strategy'
    records = db_client.query(sql)
    insert_sqls = []
    columns = ['strategyguid', 'code', 'name', 'type', 'description', 'channeltype', 'scenecode', 'version']

    for record in records:
        record = list(record)
        if record[0]:
            record[0] = long_to_guid(record[0])
        values = [sql_value(v) for v in record]
        insert_sql = f"INSERT INTO ggfw_mum_strategy ({', '.join(columns)}) VALUES ({', '.join(values)});"
        insert_sqls.append(insert_sql)

    show_sql = ('<br>'.join(insert_sqls) + '<br>') if insert_sqls else ''
    return show_sql

def upgrade_strategy_channel_rule():
    sql = 'select id,strategy_id,code,name,description,api_id,channel_type,channel_config,template_content from mum_strategy_channel_rule'
    records = db_client.query(sql)
    insert_sqls = []
    columns = ['id', 'strategyguid', 'code', 'name', 'description', 'apiGUID', 'channeltype', 'channelconfig',
               'templatecontent']
    for record in records:
        record = list(record)
        if record[0]:
            record[0] = long_to_guid(record[0])
        if record[1]:
            record[1] = long_to_guid(record[1])
        if record[5]:
            record[5] = long_to_guid(record[5])
        values = [sql_value(v) for v in record]
        insert_sql = f"INSERT INTO ggfw_mum_strategy_channel_rule ({', '.join(columns)}) VALUES ({', '.join(values)});"
        insert_sqls.append(insert_sql)

    show_sql = ('<br>'.join(insert_sqls) + '<br>') if insert_sqls else ''
    return show_sql

def upgrade_accessor_strategy():
    sql = 'select id,accessor_id,tenant_code,strategy_id,strategy_type,strategy_code,channel_type,scene_code from mum_accessor_strategy'
    records = db_client.query(sql)
    insert_sqls = []
    columns = [
        'id',
        'accessorguid',
        'tenantcode',
        'strategyguid',
        'strategytype',
        'strategycode',
        'channeltype',
        'scenecode'
    ]
    for record in records:
        record = list(record)
        if record[0]:
            record[0] = long_to_guid(record[0])
        if record[1]:
            record[1] = long_to_guid(record[1])
        if record[3]:
            record[3] = long_to_guid(record[3])
        values = [sql_value(v) for v in record]
        insert_sql = f"INSERT INTO ggfw_mum_accessor_strategy ({', '.join(columns)}) VALUES ({', '.join(values)});"
        insert_sqls.append(insert_sql)

    show_sql = ('<br>'.join(insert_sqls) + '<br>') if insert_sqls else ''
    return show_sql